package exportimporterentities;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.log4j.Logger;

import api.entitites.IGarage;
import api.entitites.IMaster;
import api.entitites.IOrder;
import api.messages.Messager;

public class Export {

	private Writer garageWriter;
	private Writer masterWriter;
	private Writer orderWriter;
	private static final String NEW_LINE = "\n";
	private static final String GARAGE_PATH_CSV="garage.csv";
	private static final String MASTER_PATH_CSV="master.csv";
	private static final String ORDER_PATH_CSV="order.csv";
	private static final String DELIMITER = " ";
	private Logger log = Logger.getLogger(Export.class);

	Export() {
		try {

			garageWriter = new FileWriter(GARAGE_PATH_CSV);
			masterWriter = new FileWriter(MASTER_PATH_CSV);
			orderWriter = new FileWriter(ORDER_PATH_CSV);
		} catch (IOException e) {
			System.out.println(Messager.UNSUCCESS_RESAVE_DATA);
			log.fatal(Messager.UNSUCCESS_RESAVE_DATA);
			
		}

	}

	void exportGarage(List<IGarage> garages) {
		try {
			for(IGarage garage: garages){
				String s =garage.getId()+DELIMITER+garage.getNumber()+ DELIMITER + garage.getFullness();
				garageWriter.write(s);
				garageWriter.write(NEW_LINE);
			}
			
			garageWriter.close();
		} catch (IOException e) {
			log.fatal(Messager.UNSUCCESS_RESAVE_DATA);
			throw new RuntimeException(Messager.UNSUCCESS_RESAVE_DATA);
		}

	}

	void exportMaster(List<IMaster> masters) {
		try {
			for(IMaster master: masters){
				String s = master.getId()+ DELIMITER+master.getName()+ DELIMITER+ master.getEmployment();
				masterWriter.write(s);
				masterWriter.write(NEW_LINE);
			}
			masterWriter.close();
		} catch (IOException e) {
			log.fatal(Messager.UNSUCCESS_RESAVE_DATA);
			throw new RuntimeException(Messager.UNSUCCESS_RESAVE_DATA);
		}

	}

	void exportOrder(List<IOrder> orders) {

		try {
			for(IOrder ord: orders){
			SimpleDateFormat f = new SimpleDateFormat(Messager.DATE_FORMAT);
			
				String s =ord.getId()+DELIMITER+ ord.getNumber() + DELIMITER
						+ f.format(ord.getFillingDate().getTime()) + DELIMITER
						+ f.format(ord.getDeadlineDate().getTime()) + DELIMITER
						+ f.format(ord.getBeginingDate().getTime()) + DELIMITER
						+ ord.getPrice() + DELIMITER + ord.getOrderStatus().toString() + DELIMITER
						+ ord.getMaster().getId() + DELIMITER
						+ ord.getGarage().getId();
				orderWriter.write(s);
				orderWriter.write(NEW_LINE);
			}
			orderWriter.close();
		} catch (IOException e) {
			log.fatal(Messager.UNSUCCESS_RESAVE_DATA);
			throw new RuntimeException(Messager.UNSUCCESS_RESAVE_DATA);
		}
	}

}
